import React, {Component} from 'react';
import {SearchOutlined,} from '@ant-design/icons';
import {Select, Button, Modal, Space, Table} from 'antd';
import {API_URL} from "../constants";
import {getCrmFields} from "../util/util";


const ZOHO = window.ZOHO;

class IntegratedComponent extends Component {

    constructor(props) {
        super(props);
        let options = [];
        let columns = [];
        let data = [];
        let scrollWidth = [];
        props.tableProps.forEach(tables => {
            let table = tables[props.moduleName];
            if (table !== undefined) {
                options = table.options;
                columns = table.columns;
                data = table.data;
                scrollWidth = table.scrollWidth;
            }
        })
        this.state = {
            tableProps: props.tableProps,
            modalVisible: false,
            options: options,
            apiName: props.apiName,
            moduleName: props.moduleName,
            searchValue: {
                key: props.value?.id,
                value: props.value?.id,
                label: props.value?.name,
            },
            columns: columns,
            data: data,
            scrollWidth: scrollWidth,
            modalClass: {width: "1000px", height: "100%"}
        };
    }

    componentDidMount() {

    }


    handleSearch = async (value) => {
        if (value === '') {
            this.fetchAll();
            return;
        }
        try {
            const {moduleName} = this.state;
            let fields = "Name";
            if (moduleName === "Accounts") {
                fields = "Account_Name";
            }
            if (moduleName === "Products") {
                fields = "Product_Name";
            }
            let req_data = {
                parameters: {},
                method: "GET",
                url: API_URL + `/crm/v3/${moduleName}/search?criteria=(${fields}:equals:${value})`,
                param_type: 1,
            };
            let response = await ZOHO.CRM.CONNECTION.invoke("crm", req_data);
            let data = response.details.statusMessage.data;
            let options = data?.map(item => ({
                value: item.id,
                label: item.Name ? item.Name : item.Product_Name,
            }));

            this.setState({options});
        } catch (error) {
            console.error(error);
        }
    };

    fetchAll = async () => {
        try {
            const {moduleName} = this.state;
            let fields = "Name";
            if (moduleName === "Accounts") {
                fields = "Account_Name";
            }
            if (moduleName === "Products") {
                fields = "Product_Name";
            }
            let req_data = {
                parameters: {},
                method: "GET",
                url: API_URL + `/crm/v3/${moduleName}?fields=${fields}`,
                param_type: 1,
            };
            let response = await ZOHO.CRM.CONNECTION.invoke("crm", req_data);
            let data = response.details.statusMessage.data;
            let options = data?.map(item => ({
                value: item.id,
                label: item.Name ? item.Name : item.Product_Name,
            }));

            this.setState({options});
        } catch (error) {
            console.error(error);
        }
    }

    getView = async () => {
        const {moduleName, tableProps} = this.state;

        if (tableProps !== {}) {
            let integratedObj = tableProps[moduleName];
            if (integratedObj !== undefined) {
                this.setState(integratedObj)
            }
        }


        // let fields = await getCrmFields(moduleName);
        // let idMap = new Map();
        // fields.map(item => {
        //     idMap.set(item.id, item.field_label)
        // })
        // let columns = [];
        // let dataSource = [];
        // let options = [];
        //
        // await ZOHO.CRM.META.getCustomViews({"Entity": moduleName}).then(async function (data) {
        //     let defaultid = data.info.default
        //     let req_data = {
        //         parameters: {},
        //         method: "GET",
        //         url: API_URL + `/crm/v5/settings/custom_views/${defaultid}?module=${moduleName}`,
        //         param_type: 1,
        //     };
        //     let fields = [];
        //     await ZOHO.CRM.CONNECTION.invoke("crm", req_data).then((data) => {
        //         data.details.statusMessage.custom_views[0].fields.map(field => {
        //             let column = {
        //                 title: idMap.get(field.id),
        //                 dataIndex: field.api_name,
        //                 key: field.api_name,
        //             }
        //             fields.push(field.api_name)
        //             columns.push(column)
        //         })
        //     });
        //     req_data = {
        //         parameters: {},
        //         method: "GET",
        //         url: API_URL + `/crm/v3/${moduleName}?fields=${fields}`,
        //         param_type: 1,
        //     };
        //     await ZOHO.CRM.CONNECTION.invoke("crm", req_data).then((data) => {
        //         dataSource = data.details.statusMessage.data;
        //         options = dataSource.map(item => ({
        //             value: item.id,
        //             label: item.Name ? item.Name : item.Product_Name,
        //         }));
        //     });
        //
        // });
        // const scrollWidth = columns.length * 200;
        // let integratedObj = {
        //     columns: columns,
        //     scrollWidth: scrollWidth,
        //     data: dataSource,
        //     options: options,
        // };
        // this.setState(integratedObj)
        // let load = {};
        // load[moduleName] = integratedObj;
        // this.props.onLoadIntegratedObj(load)
    }

    handleOpenModal = () => {
        this.setState({modalVisible: true});
    };

    handleCloseModal = () => {
        this.setState({modalVisible: false});
    };

    handleOkModal = () => {
        this.setState({modalVisible: false});
    };

    handleChange = (value) => {
        this.setState({
            searchValue: value
        })
        this.props.onChange(value)
    }

    render() {
        const {searchValue, options, modalVisible, columns, data, scrollWidth} = this.state;
        return (
            <div style={{display: 'flex', alignItems: 'center'}}>
                {/*<Space.Compact>*/}

                {/*<Button onClick={this.handleOpenModal} style={{width: '20%'}}>*/}
                {/*    <div style={{display: 'flex', alignItems: 'center'}}>*/}
                {/*        <SearchOutlined style={{marginRight: 8}}/>*/}
                {/*    </div>*/}
                {/*</Button>*/}
                {/*</Space.Compact>*/}
                <Select
                    labelInValue
                    showSearch
                    value={searchValue}
                    placeholder="Search..."
                    filterOption={false}
                    allowClear={true}
                    options={options}
                    optionLabelProp="label"
                    onChange={this.handleChange}
                    onSearch={this.handleSearch}
                    style={{width: '70%', flex: 1}}
                />
                <Modal
                    open={modalVisible}
                    onCancel={this.handleCloseModal}
                    onOk={this.handleOkModal}
                    cancelText={"取消"}
                    okText={"确认"}
                    centered
                    style={{width: '80%', height: '80%'}}
                >
                    <Table columns={columns} dataSource={data} scroll={{x: scrollWidth}}/>
                </Modal>
            </div>
        );
    }


}


export default IntegratedComponent;